package blue.mqtt4j.server.net;

import blue.mqtt4j.server.config.Config;
import blue.mqtt4j.server.config.ConfigItem;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttConnectMessage;
import io.netty.handler.codec.mqtt.MqttConnectPayload;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttConnectVariableHeader;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jin Zheng
 * @since 2020-03-22
 */
public class MqttConnectHandler extends SimpleChannelInboundHandler<MqttConnectMessage>
{
	private static Logger logger = LoggerFactory.getLogger(MqttConnectHandler.class);

	private final String username;
	private final String password;

	public MqttConnectHandler()
	{
		Config config = Config.getInstance();
		this.username = config.getString(ConfigItem.USER_NAME, ConfigItem.USER_NAME_VALUE);
		this.password = config.getString(ConfigItem.PASSWORD, ConfigItem.PASSWORD_VALUE);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, MqttConnectMessage message) throws Exception
	{
		MqttFixedHeader fixedHeader = message.fixedHeader();
		MqttConnectVariableHeader variableHeader = message.variableHeader();
		MqttConnectPayload payload = message.payload();
		logger.info("fixedHeader: {}", fixedHeader);
		logger.info("variableHeader: {}", variableHeader);
		logger.info("payload: {}", payload);

		this.connectAck(ctx, fixedHeader, MqttConnectReturnCode.CONNECTION_ACCEPTED);
	}

	private void connectAck(ChannelHandlerContext ctx, MqttFixedHeader reqHeader,
	                        MqttConnectReturnCode code)
	{
		boolean session = code == MqttConnectReturnCode.CONNECTION_ACCEPTED ? true : false;
		MqttMessage message = MqttMessageBuilders.connAck()
				.returnCode(code).sessionPresent(session).build();
		ctx.writeAndFlush(message);
	}
}
